import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import { useEffect } from 'react';
import { useState } from 'react';

// 上传之前验证图片的格式和大小
const beforeUpload = (file) => {
    // console.log('beforeUpload-file',file)
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

// UploadImg组件
const UploadImg = (props) => {
    const {imageUrl,setImageUrl} = props
    const [loading, setLoading] = useState(false);
    //对上传图片的处理
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            let { response: { url } } = info.file
            setImageUrl(url)
            setLoading(false)

        }
    };

    //上传按钮的显示
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传图片
            </div>
        </div>
    );


    // 组件的模板
    return (
        <>
            <Upload
                // 1. 修改name属性
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                //2. 修改action
                action="/api/upload"
                //3. 添加token
                headers={
                    { Authorization: 'Bearer ' + sessionStorage.getItem("token") }
                }
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? (
                    <img
                        src={imageUrl}
                        alt="avatar"
                        style={{
                            width: '100%',
                        }}
                    />
                ) : (
                    uploadButton
                )}
            </Upload>
        </>
    );
};
export default UploadImg;